import axios from 'axios'
import qs from 'qs'
import { Indicator } from 'mint-ui'
import PromiseState from './PromiseState'

const { config } = window // 本项目依赖于 window.config 的配置，格式参考 deploy-cfg-example.js
const API = axios.create({
  // baseURL: config.APIRoot,
  baseURL: config.MODE == 'dev' ? config.APIRootDev : config.APIRoot
})
// API.defaults.headers.common['content-type'] = 'text/plain';
// API.defaults.headers.common['content-type'] = 'application/x-www-form-urlencoded';

// 只有以下三种类型不会发起 Preflighted requests
// application/x-www-form-urlencoded
// multipart/form-data
// text/plain

/* eslint no-param-reassign:0 */
export default {
  methods: {
    newStore() {
      return new PromiseState()
    },
    spost(store, path, data) {
      // 弹出等待
      Indicator.open('加载中...')
      return new Promise((resolve, reject) => {
        store.b = new Date()
        store.t = 'ajax'
        store.u = path
        store.r = data
        store.p = true
        store.o = false
        store.e = false
        store.m = ''
        store.d = {}
        store.s += 1
        data = Object.assign({}, data) || {}

        // 没登录，发送 ajax 请求直接按异常处理，不实际发出请求了
        // if (this.$store && this.$store.state.session && !this.$store.state.session.cookies) {
        //   store.o = false;
        //   store.e = true;
        //   store.m = '未登录';
        //   reject(store);
        //   return;
        // }

        // 没登录，发送 ajax 请求直接按异常处理，不实际发出请求了
        // if (path != '/doctor/WeixinLogin.lg') {
        // if (sessionStorage.getItem('rybToken') == '' || sessionStorage.getItem('rybToken') == null || sessionStorage.getItem('rybToken') == undefined) {
        //   store.o = false;
        //   store.e = true;
        //   store.m = '转登录';
        // alert('转登录');
        //   this.$router.push('/index.0');
        //   reject(store);
        //  return;
        // }
        // }

        // if (this.$store && this.$store.state.session) {
        // Object.assign(data, this.$store.state.session.cookies);
        // }
        path =
          (path.indexOf('?') > 0 ? path : `${path}?`) +
          (path.indexOf('&ajax=y') > 0 ? ':' : '&ajax=y')
        // API.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
        // API.defaults.headers['Ryb-Token'] = localStorage.getItem('RYBTOKEN');
        // API.defaults.transformRequest = [d => qs.stringify(d)];

        let post

        const rybToken = localStorage.getItem(`RYBTOKEN.${config.LT}`)

        if (rybToken && rybToken != '') {
          post = API.post(path, data, {
            transformRequest: [d => qs.stringify(d)],
            headers: { 'Ryb-Token': rybToken }
          })
        } else {
          post = API.post(path, data, {
            transformRequest: [d => qs.stringify(d)]
          })
        }

        post
          .then(res => {
            Indicator.close()
            const d = res.data
            store.f = new Date()
            store.p = false
            store.c = 0
            store.d = d
            store.o = true
            store.e = false
            this.$emit(`ajax:${store.u}`, store)
            if (d.errCode && d.errCode == '101') {
              console.info('登录token失效')
              localStorage.removeItem(`RYBTOKEN.${config.LT}`)
              this.$router.push('/')
              reject(store)
            }
            resolve(store)
          })
          .catch(d => {
            Indicator.close()
            store.f = new Date()
            store.p = false
            store.o = false
            store.e = true
            store.c = -2
            if (d.status === 404) {
              store.m = '后台服务暂未开通'
            } else {
              store.m = '服务调用异常'
            }
            store.d = d
            this.$emit(`ajax:${store.u}`, store)
            reject(store)
          })
      })

      // 退出等待提示
    },
    sget(store, path, data) {
      // 弹出等待
      Indicator.open('加载中...')
      return new Promise((resolve, reject) => {
        store.b = new Date()
        store.t = 'ajax'
        store.u = path
        store.r = data
        store.p = true
        store.o = false
        store.e = false
        store.m = ''
        store.d = {}
        store.s += 1
        data = Object.assign({}, data) || {}

        // 没登录，发送 ajax 请求直接按异常处理，不实际发出请求了
        /*
        if (this.$store && this.$store.state.session && !this.$store.state.session.cookies) {
          store.o = false;
          store.e = true;
          store.m = '未登录';
          reject(store);
          return;
        }
        if (this.$store && this.$store.state.session) {
          Object.assign(data, this.$store.state.session.cookies);
        }
        */
        const get = API.get(path, { params: data })
        get
          .then(res => {
            Indicator.close()
            const d = res.data
            store.f = new Date()
            store.p = false
            store.o = true
            store.e = false
            store.c = 0
            store.d = d
            this.$emit(`ajax:${store.u}`, store)
            resolve(store)
          })
          .catch(d => {
            Indicator.close()
            store.f = new Date()
            store.p = false
            store.o = false
            store.e = true
            store.c = -2
            if (d.status === 404) {
              store.m = '后台服务暂未开通'
            } else {
              store.m = '服务调用异常'
            }
            store.d = d
            this.$emit(`ajax:${store.u}`, store)
            reject(store)
          })
      })
    },
    async sleep(seconds) {
      await new Promise(resolve => {
        setTimeout(resolve, seconds * 1000)
      })
    }
  }
}
